package com.angle.fastgo.product.service.impl;

import com.angle.fastgo.product.entity.CategoryBrandRelationEntity;
import com.angle.fastgo.product.service.CategoryBrandRelationService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.angle.fastgo.common.utils.PageUtils;
import com.angle.fastgo.common.utils.Query;

import com.angle.fastgo.product.dao.BrandDao;
import com.angle.fastgo.product.entity.BrandEntity;
import com.angle.fastgo.product.service.BrandService;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {

        QueryWrapper<BrandEntity> queryWrapper = new QueryWrapper<>();

        String searchKey = (String) params.get("key");
        if(!StringUtils.isEmpty(searchKey)) {
            queryWrapper.eq("brand_id",searchKey).or().like("name",searchKey);
        }

        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void updateByIdWithRelDate(BrandEntity brand) {
        //修改品牌表数据
        this.updateById(brand);
        //修改了品牌名称,那么我们需要修改级联数据
        if(!StringUtils.isEmpty(brand.getName())) {
            CategoryBrandRelationEntity categoryBrandRelationEntity = new CategoryBrandRelationEntity();
            categoryBrandRelationEntity.setBrandId(brand.getBrandId());
            categoryBrandRelationEntity.setBrandName(brand.getName());
            UpdateWrapper<CategoryBrandRelationEntity> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("brand_id",brand.getBrandId());
            categoryBrandRelationService.update(categoryBrandRelationEntity,updateWrapper);
        }
    }

}